package cc.linker.steplink.crm.merchanth5.service.impl;

import cc.linker.steplink.crm.commons.http.HttpService;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.utils.NumberUtils;
import cc.linker.steplink.crm.commons.utils.SignUtils;
import cc.linker.steplink.crm.merchanth5.dao.MallDao;
import cc.linker.steplink.crm.merchanth5.dao.acs.ExternalOrderDao;
import cc.linker.steplink.crm.merchanth5.service.MallBoomService;
import cc.linker.steplink.crm.merchanth5.service.acs.ExternalOrderService;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class ExternalOrderServiceImpl implements ExternalOrderService {

    @Autowired
    private ExternalOrderDao externalOrderDao;
    @Autowired
    private SystemProperties systemProperties;
    @Autowired
    private HttpService httpService;
    @Autowired
    private MallDao mallDao;
    @Autowired
    private MallBoomService mallBoomService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Value("${lm.service.url}")
    private String apiUrl;

    /**
     * 调用江苏台erp同步接口
     *
     * @param : orderSn
     * @return
     */
    @Async
    @Override
    public void synchronizationOrder(String orderSn) {
        try {
            Map map = this.getOrder(orderSn);
            if (map != null && map.size() > 0) {
                LOGGER.info("调用江苏台erp同步接口开始");
                // 请求erp结果
                String result = "";
                //erp地址，暂时没有
                String url = systemProperties.getErpUrl() + "/??";
                Map<String, String> header = new HashMap<String, String>() {{
                    put("Content-Type", "application/json;charset=UTF-8");
                }};
                result = httpService.doPost(url, JSON.toJSONString(map), header);
                LOGGER.info("调用江苏台erp同步接口结束---->>>>>>   " + result);
            }

        } catch (Exception e) {
            e.printStackTrace();
            //LOGGER.error("蜻蜓支付调用异常", e);
        }
    }

    /**
     * 调用江苏台erp退款发货接口
     *
     * @param : orderSn
     * @return
     */
    @Async
    @Override
    public void synchronizationRefund(Long recId) {
        try {
            Map map = this.getRefundOrder(recId);
            if (map != null && map.size() > 0) {
                LOGGER.info("调用江苏台erp退款发货接口开始");
                // 请求erp结果
                String result = "";
                //erp地址，暂时没有
                String url = systemProperties.getErpUrl() + "/??";
                Map<String, String> header = new HashMap<String, String>() {{
                    put("Content-Type", "application/json;charset=UTF-8");
                }};
                result = httpService.doPost(url, JSON.toJSONString(map), header);
                LOGGER.info("调用江苏台erp退款发货接口结束---->>>>>>   " + result);
            }

        } catch (Exception e) {
            e.printStackTrace();
            //LOGGER.error("蜻蜓支付调用异常", e);
        }
    }

    @Override
    public Map getOrder(String orderSn) {
        Map map = new HashMap();
        if (!StringUtils.isEmpty(orderSn)) {
            map = externalOrderDao.getOrder(orderSn);
            if (map == null) {
                throw GlobalException.build("未找到对应订单！");
            }
            String addressPhone = "";
            if (map.get("addressPhone") != null) {
                addressPhone = map.get("addressPhone").toString();
            }
            if (StringUtils.isEmpty(addressPhone)) {
                String customerId = "";
                if (map.get("customerId") != null) {
                    customerId = map.get("customerId").toString();
                }
                String bindPhone = externalOrderDao.getBindPhoneByCid(customerId);
                map.put("addressPhone", bindPhone);
            }
            Long orderId = 0l;
            if (map.get("orderId") != null) {
                orderId = Long.valueOf(map.get("orderId").toString());
            }
            List<Map> orderGoodsList = externalOrderDao.getOrderGoodsList(orderId);
            if (orderGoodsList != null && orderGoodsList.size() > 0) {
                map.put("orderGoodsList", orderGoodsList);
                return map;
            } else {
                throw GlobalException.build("请先设置对应sku！");
            }
        }
        return null;
    }

    @Override
    public Map getRefundOrder(Long recId) {
        Map map = new HashMap();
        if (!StringUtils.isEmpty(recId)) {
            map = externalOrderDao.getRefundOrder(recId);
            if (map != null) {
                return map;
            } else {
                throw GlobalException.build("未找到对应订单!");
            }

        }
        return null;
    }

    @Override
    public void addAbnormalReason(Map<String, Object> param) {
        externalOrderDao.addAbnormalReason(param);
    }

    @Override
    public List<Map> getOrderList(String startTime) {
        List<Map> mapList = new ArrayList<Map>();
        if (!StringUtils.isEmpty(startTime)) {
            List<Map> mapListNew = externalOrderDao.getOrderList(startTime);
            if (mapListNew == null || mapListNew.size() == 0) {
                throw GlobalException.build("未找到对应订单！");
            }
            mapListNew.forEach(map -> {
                String addressPhone = "";
                if (map.get("addressPhone") != null) {
                    addressPhone = map.get("addressPhone").toString();
                }
                if (StringUtils.isEmpty(addressPhone)) {
                    String customerId = "";
                    if (map.get("customerId") != null) {
                        customerId = map.get("customerId").toString();
                    }
                    String bindPhone = externalOrderDao.getBindPhoneByCid(customerId);
                    map.put("addressPhone", bindPhone);
                }
                Long orderId = 0l;
                if (map.get("orderId") != null) {
                    orderId = Long.valueOf(map.get("orderId").toString());
                }
                List<Map> orderGoodsList = externalOrderDao.getOrderGoodsList(orderId);
                if (orderGoodsList != null && orderGoodsList.size() > 0) {
                    map.put("orderGoodsList", orderGoodsList);
                    mapList.add(map);
                }
            });
        }
        return mapList;
    }

    @Override
    public PageInfo getOrderListByPhone(Map<String, Object> par, Integer pageIndex, Integer pageSize) {
        //根据手机号获取customerId
        Map<String, Object> param = new HashMap<>();
        param.put("phone", par.get("phone"));
        param.put("orgId", "10065");
        String customerId = externalOrderDao.getCustomerIdByPhone(param);
        if (StringUtils.isEmpty(customerId)) {
            throw GlobalException.build("该手机号没有被绑定！");
        }
        PageHelper.startPage(pageIndex, pageSize);
        par.put("customerId", customerId);
        //根据customerId获取订单列表
        List<Map> mapListNew = externalOrderDao.getOrderListByCustomerId(par);
        //获取用户信息
        Map<String, Object> userInfo = mallBoomService.getCustomerInfoByCustomerId(customerId);
        if (null != userInfo) {
            userInfo.remove("customerName");
            userInfo.remove("orgId");
            userInfo.remove("promoterStatus");
        }
        mapListNew.forEach(orderInfo -> {
            orderInfo.put("orderTotalPrice", NumberUtils.fenToYuan(Long.valueOf(orderInfo.get("orderTotalPrice").toString())));
            orderInfo.put("goodsAmount", NumberUtils.fenToYuan(Long.valueOf(orderInfo.get("goodsAmount").toString())));
            orderInfo.put("shippingFee", NumberUtils.fenToYuan(Long.valueOf(orderInfo.get("shippingFee").toString())));
            Map<String, Object> shareUserInfo = new HashMap<>();
            if (!StringUtils.isEmpty(orderInfo.get("salerId"))) {
                String salerId = orderInfo.get("salerId").toString();
                shareUserInfo = mallBoomService.getCustomerInfoByCustomerId(salerId);
                if (null != shareUserInfo) {
                    shareUserInfo.remove("customerName");
                    shareUserInfo.remove("orgId");
                    shareUserInfo.remove("promoterStatus");
                }
                orderInfo.put("isShareOrder", true);
            } else {
                orderInfo.put("isShareOrder", false);
            }
            long orderId = Long.valueOf(orderInfo.get("orderId").toString());
            List<Map> orderGoodsList = externalOrderDao.getOrderGoodsList(orderId);
            if (null != orderGoodsList && orderGoodsList.size() > 0) {
                for (Map da : orderGoodsList) {
                    da.remove("recId");
                    da.remove("goodsId");
                    da.remove("shippingType");
                    da.remove("status");
                    da.remove("productCode");
                    da.remove("productId");
                    da.remove("goodsPrice");
                }
            }
            orderInfo.remove("integralPaymentAmount");
            orderInfo.remove("salerId");
            orderInfo.remove("orderAmount");
            orderInfo.remove("orderId");
            orderInfo.remove("customerId");
            orderInfo.put("orderGoods", orderGoodsList);
            orderInfo.put("shareUserInfo", shareUserInfo);
            orderInfo.put("userInfo", userInfo);

        });
        return new PageInfo(mapListNew);
    }

    @Override
    public void summaryEnd(String orderSn, Integer num) {
        try {
            if (!StringUtils.isEmpty(orderSn)) {
                Map<String, Object> orderInfo = mallDao.getOrderInfoBySn(orderSn);
                if (null != orderInfo && "10065".equals(orderInfo.get("orgId"))) {
                    orderInfo.put("orderTotalPrice", NumberUtils.fenToYuan(Long.valueOf(orderInfo.get("orderTotalPrice").toString())));
                    orderInfo.put("goodsAmount", NumberUtils.fenToYuan(Long.valueOf(orderInfo.get("goodsAmount").toString())));
                    orderInfo.put("shippingFee", NumberUtils.fenToYuan(Long.valueOf(orderInfo.get("shippingFee").toString())));
                    String customerId = orderInfo.get("customerId").toString();
                    Map<String, Object> shareUserInfo = new HashMap<>();
                    if (!StringUtils.isEmpty(orderInfo.get("salerId"))) {
                        String salerId = orderInfo.get("salerId").toString();
                        shareUserInfo = mallBoomService.getCustomerInfoByCustomerId(salerId);
                        if (null != shareUserInfo) {
                            shareUserInfo.remove("customerName");
                            shareUserInfo.remove("orgId");
                            shareUserInfo.remove("promoterStatus");
                        }
                        orderInfo.put("isShareOrder", true);
                    } else {
                        orderInfo.put("isShareOrder", false);
                    }
                    long orderId = Long.valueOf(orderInfo.get("orderId").toString());
                    List<Map> orderGoodsList = externalOrderDao.getOrderGoodsList(orderId);
                    if (null != orderGoodsList && orderGoodsList.size() > 0) {
                        for (Map da : orderGoodsList) {
                            da.remove("recId");
                            da.remove("goodsId");
                            da.remove("shippingType");
                            da.remove("status");
                            da.remove("productCode");
                            da.remove("productId");
                            da.remove("goodsPrice");
                        }
                    }
                    Map<String, Object> userInfo = mallBoomService.getCustomerInfoByCustomerId(customerId);
                    if (null != userInfo) {
                        userInfo.remove("customerName");
                        userInfo.remove("orgId");
                        userInfo.remove("promoterStatus");
                    }
                    orderInfo.remove("integralPaymentAmount");
                    orderInfo.remove("salerId");
                    orderInfo.remove("orderAmount");
                    orderInfo.remove("orderId");
                    orderInfo.remove("customerId");

                    Map<String, Object> map = new HashMap<>();
                    map.put("orderInfo", orderInfo);
                    map.put("orderGoods", orderGoodsList);
                    map.put("shareUserInfo", shareUserInfo);
                    map.put("userInfo", userInfo);
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                    String paramsStr = JSON.toJSONString(map, SerializerFeature.WriteMapNullValue);
                    Map<String, Object> paramMap = new HashMap<>();
                    paramMap.put("biz_data", URLEncoder.encode(paramsStr, "GBK"));
                    paramMap.put("timestamp", df.format(new Date()));
                    String sign = SignUtils.generateSignature(paramMap, "YGyt3DBePqHFyUIlpvEgIadILjn1edHo");
                    paramMap.put("sign", sign);
                    if (StringUtils.isEmpty(apiUrl)) {
                        Map<String, Object> errorMap = new HashMap<>();
                        errorMap.put("orderSn", orderSn);
                        errorMap.put("sendNum", num);
                        stringRedisTemplate.opsForList().rightPush("lm_task_list:", JSON.toJSONString(errorMap));
                    } else {
                        String res = httpService.doPost(apiUrl, paramMap, null);
                        if (!res.equals("success")) {
                            Map<String, Object> errorMap = new HashMap<>();
                            errorMap.put("orderSn", orderSn);
                            errorMap.put("sendNum", num);
                            stringRedisTemplate.opsForList().rightPush("lm_task_list:", JSON.toJSONString(errorMap));
                        }
                        LOGGER.info("订单结算完成通知完成：" + res);
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("订单结算完成通知异常", e);
        }
    }
}

